﻿using EmitMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSite.Data.NH.Repositories;
using WebSite.Model;
using WebSite.Web.Models;
using WebSite.Web.SessionAndFilter;
using WebSite.Core;

namespace WebSite.Web.Controllers.Admin
{
    [AuthorAttribute]
    public class HomeController : Controller
    {
        private readonly IMoudleRepository mr;
        private readonly IAdminUserRepository admin;
        private readonly IUnitOfWork uow;
        public HomeController(IMoudleRepository mr, IAdminUserRepository admin, IUnitOfWork uow)
        {
            this.mr = mr;
            this.admin = admin;
            this.uow = uow;
        }

        public ActionResult Index()
        {
            ViewBag.UserName = Sessions.User.TrueName;
            return View();
        }
        /// <summary>
        /// 欢迎页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Welcome()
        {
            return View();
        }
        /// <summary>
        /// 登陆界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Login(string rtnId)
        {
            if (!string.IsNullOrEmpty(rtnId))
            {
                switch (rtnId)
                {
                    case "1":
                        ViewBag.ErrorMessage = "<font color='red'>验证码输入不正确</font> <script type=\"text/javascript\">" +
                       "setTimeout(function () {$(\"#randomCode\").focus(); $(\"#disMess\").html(\"\"); }, 2000);  </script>";
                        break;
                    case "2":
                        ViewBag.ErrorMessage = "<font color='red'>用户名或密码错误</font> <script type=\"text/javascript\">" +
    "setTimeout(function () {$(\"#passWord\").focus(); $(\"#disMess\").html(\"\"); }, 2000);  </script>";
                        break;
                }
            }
            return View();
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <returns>1验证码错误，2用户名密码错误</returns>
        public ActionResult LoginData(string userName, string passWord, string randomCode)
        {
            if (randomCode.ToUpper().Equals(Sessions.ValidateCode))
            {
                AdminUserInfo info = admin.Login(userName.Trim().Replace("'", "").Replace("-", ""), passWord.Trim().Replace("'", "").Replace("-", ""));
                AdminUserVM vm = new AdminUserVM();
                ObjectsMapper<AdminUserInfo, AdminUserVM> mapper = ObjectMapperManager.DefaultInstance.GetMapper<AdminUserInfo, AdminUserVM>();
                vm = mapper.Map(info);
                if (info != null)
                {
                    Sessions.User = vm;
                    return RedirectToAction("Index");

                }
                else
                {
                    return RedirectToAction("Login", new { rtnId = "2" });

                }
            }
            else
            {
                return RedirectToAction("Login", new { rtnId = "1" });

            }
        }


        /// <summary>
        /// 注销
        /// </summary>
        /// <returns>登录页面</returns>
        public ActionResult LoginOut()
        {
            Session.Abandon();
            return RedirectToAction("Login");
        }

        /// <summary>
        /// 修改密码视图
        /// </summary>
        /// <returns></returns>
        public ActionResult ChangePassword()
        {
            AdminUserVM vm = null;
            AdminUserInfo info = admin.GetAdminInfo(Sessions.User.UserId);
            ObjectsMapper<AdminUserInfo, AdminUserVM> mapper = ObjectMapperManager
                                                      .DefaultInstance
                                                      .GetMapper<AdminUserInfo, AdminUserVM>();
            vm = mapper.Map(info);
            vm.Password = "";//初始化旧密码为空
            return View(vm);
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="passwordVM"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangePassword(AdminUserVM vm)
        {


            var flag = false;
            if (ModelState.IsValid)
            {
                AdminUserInfo info = admin.GetAdminInfo(vm.UserId);
                //判断旧密码是否正确
                if (info.Password.Equals(WebSite.Data.NH.Repositories.AdminUserRepository.MD5Crypt.Encrypt(vm.Password)))
                {
                    info.Password = vm.NewPass;
                    flag = admin.UpdatePassWord(info);
                    uow.Commit();
                    ViewBag.ErrorMessage = "<font color='red'>密码修改成功</font> <script type=\"text/javascript\">" +
                  "setTimeout(function () { $(\"#disMess\").html(\"\"); }, 2000);  </script>";
                }
                else
                {

                    ViewBag.ErrorMessage = "<font color='red'>旧密码不正确</font> <script type=\"text/javascript\">" +
                     "setTimeout(function () { $(\"#disMess\").html(\"\"); }, 2000);  </script>";
                }
            }
            return View();
        }
        /// <summary>
        /// 生产验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult RandomCode(string time)
        {
            RandomCodeInfo ran = new RandomCodeInfo();
            string strKey = "";
            byte[] data = ran.GenerateVerifyImage(5, ref strKey);
            Sessions.ValidateCode = strKey;
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            System.Web.HttpContext.Current.Response.OutputStream.Write(data, 0, data.Length);
            return PartialView();
        }

        /// <summary>
        /// 加载模块
        /// </summary>
        /// <returns></returns>
        public JsonResult Module()
        {
            ObjectsMapper<MoudleInfo, ModuleVM> mapper = ObjectMapperManager
                                                        .DefaultInstance
                                                        .GetMapper<MoudleInfo, ModuleVM>();
            var userCompanyId = Sessions.User.CompanyId;
            var modules = mr.GetAllMoudle(userCompanyId);
            IList<ModuleVM> modulesVm = mapper.MapEnum(modules).ToList();
            IList<ModuleVM> treeData = new List<ModuleVM>();

            var parentMoudle = modulesVm.Where(e => e.ParentId == 0);
            foreach (var item in parentMoudle)
            {
                var subs = modulesVm.Where(e => e.ParentId == item.MoudleId);

                item.id = item.MoudleId.ToString();

                if (subs == null || subs.Count() == 0)
                {
                    item.isLeaf = true;
                }
                else
                {
                    item.isLeaf = false;
                    item.isexpand = true;
                    foreach (var itemSub in subs)
                    {
                        itemSub.isLeaf = true;
                        itemSub.id = itemSub.MoudleId.ToString();
                        item.children.Add(itemSub);
                    }
                }
                treeData.Add(item);
            }

            return Json(treeData, JsonRequestBehavior.AllowGet);
        }
    }
}
